package net.zoneland.geological.usermanage.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.json.JSONObject;
import net.zoneland.geological.usermanage.entity.Tbl_role;
import net.zoneland.geological.usermanage.entity.Tbl_user;
import net.zoneland.geological.usermanage.entity.Tbl_user_role;
import net.zoneland.geological.usermanage.service.Tbl_roleServiceI;
import net.zoneland.geological.usermanage.service.Tbl_userServiceI;
import net.zoneland.geological.usermanage.service.Tbl_user_roleServiceI;
import net.zoneland.greenleaf.system.controller.BaseController;
import net.zoneland.greenleaf.utils.HttpClientUtil;

@Controller
@RequestMapping("/")
public class LoginController extends BaseController{
	/**
	 * 如果需要系统对此Controller的访问进行监控，记录服务访问的时间，耗时，那么请将monitor属性设置为“true”
	 */
	public boolean monitor = false;
	
	public static Logger logger = Logger.getLogger(LoginController.class);
	
	@SuppressWarnings("unused")
	private String clazzName = new Object() {  
        public String getClassName() {  
            String clazzName = this.getClass().getName();  
            return clazzName.substring(0, clazzName.lastIndexOf('$'));  
        }  
    }.getClassName();
	
    @Autowired
	private Tbl_userServiceI tbl_userService;
    
    @Autowired
	private Tbl_user_roleServiceI tbl_user_roleService;
    
    @Autowired
	private Tbl_roleServiceI tbl_roleService;
    
    /**
	 * 获取当前登录用户信息
	 * @param id
	 * @return
	**/
	@RequestMapping( method = RequestMethod.GET, value = "/currentPerson", produces = "text/html;charset=UTF-8" )
	@ResponseBody
	public Object currentPerson(){
		Map<String, Object> map = new HashMap<String, Object>();

		try{
			map.put( "currentPerson", this.getSession().getAttribute( "login_user" ) );
			
			if (isAdmin((Tbl_user)this.getSession().getAttribute( "login_user" ))) {
				map.put("currentRole", "ADMIN");
			}
			map.put( "result", "success");
		}catch( Exception e ){
			map.put( "result", "error");
			map.put( "message", "获取登录用户信息时发生异常!");
			e.printStackTrace();
		}
		return map;
	}
    
	 @RequestMapping( method = RequestMethod.GET, value = "/logout" )
	 @ResponseBody
	 public Object logout() {
		 Map<String, Object> map = new HashMap<String, Object>();
			try{
				this.getSession().setAttribute( "login_user", null );
				map.put( "result", "success");
			}catch( Exception e ){
				map.put( "result", "error");
				map.put( "message", "用户退出系统时发生异常!");
				e.printStackTrace();
			}
		 return map; 
	 }
	
    @RequestMapping( method = RequestMethod.POST, value = "/login" )
    @ResponseBody
	public Object login( @RequestBody Map<String, Object> paramMap ) {
    	Map<String, Object> map=new HashMap<String,Object>();
    	Map<String, Object> queryMap =new HashMap<String,Object>();
    	Tbl_user tbl_user = null;
    	String login_name = null;
    	String login_password = null;
    	String password = null;
    	String host = null;
    	Boolean check = true;
    	
    	if( paramMap == null ){
			check = false;
			map.put( "result", "error");
			map.put( "message", "登录用户信息为空，无法登录系统!");
		}
    	if( check ){
    		host = this.getRequest().getRemoteHost();
    		if( paramMap.get( "login_name" ) == null ){
    			check = false;
    			map.put( "result", "error");
    			map.put( "message", "用户登录账号为空，无法登录系统!");
    		}else{
    			login_name = paramMap.get( "login_name" ).toString().trim();
    		}
    	}
    	if( check ){
    		if( paramMap.get( "login_password" ) == null ){
    			check = false;
    			map.put( "result", "error");
    			map.put( "message", "用户登录密码为空，无法登录系统!");
    		}else{
    			login_password = paramMap.get( "login_password" ).toString().trim();
    		}
    	}
    	if( check ){
    		queryMap.put( "login_name", login_name );
    		try {
    			tbl_user = tbl_userService.get( queryMap );
    			if( tbl_user == null ){
    				check = false;
        			map.put( "result", "error");
        			map.put( "message", "用户不存在!登录账号：" + login_name);
    			}
			} catch (Exception e) {
				check = false;
    			map.put( "result", "error");
    			map.put( "message", "系统根据账号获取用户信息时发生异常!");
				logger.error( "系统根据账号获取用户信息时发生异常!", e );
			}
    	}
    	if( check ){
    		try {
				password = tbl_userService.getUserPassword( login_name );
			} catch (Exception e) {
				check = false;
    			map.put( "result", "error");
    			map.put( "message", "系统获取用户登录密码时发生异常!");
				logger.error( "系统获取用户登录密码时发生异常", e );
			}
    	}
    	if( check ){
    		if( password != null && password.equals( login_password )){
    			queryMap.put( "login_name", login_name );
    			queryMap.put( "login_ip", host );
    			queryMap.put( "login_time", new Date() );
    			try {
					tbl_userService.recordLogin( queryMap );
				} catch (Exception e) {
					e.printStackTrace();
				}
    			queryMap.clear();
    			queryMap.put( "login_name", login_name );
    			try {
    				tbl_user = tbl_userService.get(queryMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
    			this.getSession().setAttribute( "login_user", tbl_user );
    			
    			try {
					if (isAdmin(tbl_user)) {
						this.getSession().setAttribute( "login_user_role", "ADMIN" );
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    			
    			map.put( "result", "success" );
    			map.put( "message", "系统查询信息数据成功！" );
    		}else{
    			check = false;
    			map.put( "result", "error");
    			map.put( "message", "用户名密码不正确!");
    		}
    	}
		return map;
	}
    
    private boolean isAdmin(Tbl_user user) throws Exception {
    	
    	if (user == null) {
    		return false;
    	}
    	
    	Map<String, Object> queryMap =new HashMap<String,Object>();
    	queryMap.put("code", "ADMIN");
    	
    	//查询ADMIN角色
    	Tbl_role role = tbl_roleService.get(queryMap);
    	
    	queryMap.clear();
    	queryMap.put("user_id", user.getId());
    	
    	//查询当前用户的所有角色
    	List<Tbl_user_role> userRoleList = tbl_user_roleService.getList(queryMap);
    	
    	for (Tbl_user_role userRole : userRoleList) {
    		if (role.getId().equals(userRole.getRole_id())) {
    			return true;
    		}
    	}
    	
    	return false;
    }
    
    @RequestMapping( method = RequestMethod.GET, value = "/ssologin" )
    @ResponseBody
	public Object ssoLogin( HttpServletRequest request ) {
    	Map<String, Object> map=new HashMap<String,Object>();
    	map.put( "result", "error");
		map.put( "message", "登录失败!");
    	
    	String ssoURL = "http://183.233.90.236:8080/DCIWebService/rest/szcwm";
    	
    	String token = request.getParameter("token");
    	
    	if (StringUtils.isNotEmpty(token)) {
    		
    		//验证token
    		ssoURL += "?action=AUTH_TICKET&content=&token=";
    		ssoURL += token;
    		
    		String responseStr = HttpClientUtil.doGet(ssoURL, null, "UTF-8", null, false);
    		
    		JSONObject result = JSONObject.fromObject(responseStr);
    		String status = result.getString("status");
    		
    		//0验证成功
    		if ("0".equals(status)) {
    			
    			Map<String, Object> queryMap = new HashMap<String, Object>();
    			queryMap.put("login_name", "viewuser");
    			try {
					Tbl_user tbl_user = tbl_userService.get( queryMap );
					
					if (tbl_user != null) {
					
						this.getSession().setAttribute( "login_user", tbl_user );
						
						map.put( "result", "success");
						map.put( "message", "登录成功!");
					}
					
				} catch (Exception e) {
					logger.error( "系统获取用户信息时发生异常", e );
				}
    			
    		} 
    		
    	}
    	
    	return map;
    }
}
